package com.wangmin.intercept.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.util.IOUtils;
import com.wangmin.intercept.activity.LoginActivity;
import com.wangmin.intercept.bean.AdFilterBean;
import com.wangmin.intercept.bean.ProtocalMsg;
import com.wangmin.intercept.utils.LogUtils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import de.greenrobot.event.EventBus;
/**
 * Created by wm on 2016/12/17.
 */
public class SocketService extends Service {
    private LogUtils logUtils;
    private MyBinder binder = new MyBinder();
    private BufferedReader bufferedReader,bufferedReaderData;
    private  BufferedWriter bufferedWriter,bufferedWriterData;
    private Socket socket,dataSocket;
    private LoginBroadCast loginBroadCast;
    private String ip;
    public class MyBinder extends Binder{
        public Service getService(){
            return SocketService.this;
        }
    }
    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        logUtils = LogUtils.getNewInstance("SocketService");
        logUtils.dob("开始启动服务SocketService");
        loginBroadCast = new LoginBroadCast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LOGIN);
        registerReceiver(loginBroadCast,intentFilter);
    }

    public void login(final String ip,final String pass){
        this.ip = ip;
        logUtils.dob("开始登陆");
        new Thread(){
            @Override
            public void run() {
                try{
                    socket = new Socket();
                    SocketAddress socAddress = new InetSocketAddress(ip, 9999);
                    socket.connect(socAddress, 15000);
                    socket.setKeepAlive(true);
                    bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
                    bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));
                    ProtocalMsg protocalMsg = new ProtocalMsg(pass,1,pass);
                    String json = JSON.toJSONString(protocalMsg);
                    new Thread(){
                        @Override
                        public void run() {
                            while (true) {
                                try {
                                    sendAndReciver(bufferedReader);
                                }catch (Exception e){
                                    logUtils.dob("发送心跳异常");
                                }
                            }
                        }
                    }.start();
                    writeData(json,bufferedWriter);
                }catch (Exception e){
                    e.printStackTrace();
                    loginResult(-1, e.getMessage());
                }
            }
        }.start();
    }

    private void connetionDataSocket(final String ip){
        new Thread(){
            @Override
            public void run() {
                try {
                    dataSocket = new Socket();
                    SocketAddress socAddress = new InetSocketAddress(ip, 10000);
                    dataSocket.connect(socAddress, 15000);
                    dataSocket.setKeepAlive(true);
                    bufferedReaderData = new BufferedReader(new InputStreamReader(dataSocket.getInputStream(), "utf-8"));
                    bufferedWriterData = new BufferedWriter(new OutputStreamWriter(dataSocket.getOutputStream(), "utf-8"));
                    loginResult(1,"登录成功");
                    while (true) {
                        sendAndReciver(bufferedReaderData);
                    }
                }catch (Exception e){
                    loginResult(-1,"登陆失败");
                }
            }
        }.start();

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public String sendAndReciver(BufferedReader bufferedReader) throws IOException {
        if (bufferedReader != null) {
            String line = bufferedReader.readLine();
            logUtils.dob("接收信息"+line);
            if(TextUtils.isEmpty(line)){
                return "";
            }
             ProtocalMsg protocalMsg1 = null;
            try {
                 protocalMsg1 = JSON.parseObject(line,ProtocalMsg.class);
            }catch (Exception e){

            }
            final ProtocalMsg protocalMsg = protocalMsg1;
            if(protocalMsg1 == null){
                LogUtils.getNewInstance("SocketService").eob("ProtocalMsg is null"+line);
                return null;
            }
            if (protocalMsg.code == 1) {
                logUtils.dob("开始发送handler");
                Message message = new Message();
                message.what = 1;
                message.obj = protocalMsg.data;
               handler.sendMessage(message);
            }else if(protocalMsg.code == 2){
                Message message = new Message();
                message.what = 2;
                message.obj = protocalMsg.data;
                handler.sendMessage(message);
            }else if(protocalMsg.code == 3){
                Message message = new Message();
                message.what = 3;
                message.obj = protocalMsg;
                handler.sendMessage(message);
            }else if(protocalMsg.code == 4){
                Message message = new Message();
                message.what = 4;
                message.obj = protocalMsg;
                handler.sendMessage(message);
            }else if(protocalMsg.code == -1){
                Message message = new Message();
                message.what = -1;
                message.obj = protocalMsg;
                handler.sendMessage(message);
            }if(protocalMsg.code == 6){
                connetionDataSocket(ip);
            }
            Log.e("json",protocalMsg.toString());
        }
        return null;
    }

    public Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 1) {
                logUtils.dob("开始发送广播");
                String url = (String) msg.obj;
                ProtocalMsg protocalMsg = new ProtocalMsg("ok",1,url);
                EventBus.getDefault().post(protocalMsg);
            }else if(msg.what == 2){
                String url = (String) msg.obj;
                ProtocalMsg protocalMsg = new ProtocalMsg("ok",2,url);
                EventBus.getDefault().post(protocalMsg);
            }else if(msg.what == 3){
               ProtocalMsg protocalMsg = (ProtocalMsg) msg.obj;
                EventBus.getDefault().post(protocalMsg);
            }else if(msg.what == 4){
                stopSelf();
                System.exit(0);
            }else if(msg.what == -1){
                ProtocalMsg protocalMsg = (ProtocalMsg) msg.obj;
                loginResult(protocalMsg.code, protocalMsg.data);
            }
        }
    };

    private void loginResult(int value, String data) {
        Intent intent = new Intent(LoginActivity.ServiceActionLogin);
        intent.putExtra("loginResult", value);
        intent.putExtra("msg", data);
        sendBroadcast(intent);
    }

    public void onEventMainThread(AdFilterBean adFilterBean){
        String json = JSON.toJSONString(adFilterBean);
        logUtils.dob("开始发送拦截条目"+ json);
        writeData(json,bufferedWriterData);
    }

    private void writeData(String json,BufferedWriter bufferedWriterData) {
        if (bufferedWriterData != null) {
            try {
                bufferedWriterData.write(json + System.getProperty("line.separator"));
                bufferedWriterData.flush();
            }catch (Exception e){

            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        logUtils.dob("服务销毁了");
        closeLoginSocket();
        closeDataSocket();
        if(loginBroadCast!=null){
            unregisterReceiver(loginBroadCast);
        }
    }

    private void closeDataSocket() {
        IOUtils.close(bufferedReaderData);
        IOUtils.close(bufferedWriterData);
        try{
            if(dataSocket!=null) {
                dataSocket.close();
            }
        }catch (Exception e){

        }
    }

    private void closeLoginSocket() {
        IOUtils.close(bufferedReader);
        IOUtils.close(bufferedWriter);
        try{
            if(socket!=null) {
                socket.close();
            }
        }catch (Exception e){

        }
    }

    public static final String LOGIN = "com.wangmin.kuaiyan.login";
    private class LoginBroadCast extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if(LOGIN.equals(intent.getAction())){
                String ip = intent.getStringExtra("ip");
                String pass = intent.getStringExtra("pass");
                login(ip,pass);
            }
        }
    }
}
